//
//  SISSDBManger.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/3/13.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSDBManger.h"


static NSString *const _dbName = @"siss_t_caches.sqlite";
static NSString *_tableName = nil;

static NSString *_dbPath = nil;

@implementation SISSDBManger

+ (void)load {
    _dbPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:_dbName];
    NSLog(@"%@", _dbPath);
}

#pragma mark - insert data
- (void)insertItem:(id)item cacheKey:(NSString *)cacheKey {
    NSString *sql = @"INSERT INTO t_caches(cache_data, cache_key, user_id) VALUES (?, ?, ?)";
    
    NSData *cacheData = [NSKeyedArchiver archivedDataWithRootObject:item];
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        BOOL result = [db executeUpdate:sql withArgumentsInArray:@[cacheData, cacheKey, [SISSUserAccount shared].spId]];
        
        if (result) {
            NSLog(@"INSERT成功");
        }else {
            NSLog(@"INSERT失败");
        }
    }];
}

- (id)itemWithCacheKey:(NSString *)cacheKey {
    
    if (!cacheKey) {
        return nil;
    }
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE cache_key = %@",_tableName,cacheKey];
    __block id obj;
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
        FMResultSet *resultSet = [db executeQuery:sql];
        
        while ([resultSet next]) {
            NSData *data = [resultSet dataForColumn:@"cache_data"];
            obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        }
    }];
    return obj;
}

#pragma mark - clear all data
- (void)clearAll {
    
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@",_tableName];
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
        BOOL result = [db executeUpdate:sql];
        
        if (result) {
            NSLog(@"更新成功");
        }else {
            NSLog(@"更新失败");
        }
    }];
}

// 查询
- (void)queryArrayOfDicts:(NSString *)sql completion:(void(^)(NSMutableArray<NSMutableDictionary *> *dictArrayM))completion {
    
    NSMutableArray<NSMutableDictionary *> *dictArrayM = [NSMutableArray array];
    
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *resultSet = [db executeQuery:sql withArgumentsInArray:@[]];
        
        while (resultSet.next) {
            
            NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
            
            for (int i = 0; i < resultSet.columnCount; i++) {
                
                NSString *colName = [resultSet columnNameForIndex:i];
                
                NSString *colValue = [resultSet objectForColumn:colName];
                
                dictM[colName] = colValue;
            }
            
            [dictArrayM addObject:dictM];
        }
        
        completion(dictArrayM);
        
    }];}


// 全部查询
- (void)queryDatas {
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@",_tableName];
    
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *resultSet = [db executeQuery:sql withArgumentsInArray:@[]];
        
        while (resultSet.next) {
            
            NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
            
            for (int i = 0; i < resultSet.columnCount; i++) {
                
                NSString *colName = [resultSet columnNameForIndex:i];
                
                NSString *colValue = [resultSet objectForColumn:colName];
                
                dictM[colName] = colValue;
            }
            NSLog(@"%@", dictM);
        }
    }];
    
}

// 查询
- (void)queryCondition {
    
    NSString *sql = @"SELECT cache_data, cache_key, user_id FROM t_caches";
    
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *resultSet = [db executeQuery:sql withArgumentsInArray:@[]];
        
        while (resultSet.next) {
            
            int userId = [resultSet intForColumn:@"user_id"];
            NSString *cacheKey = [resultSet stringForColumn:@"cache_key"];
            id cacheData = [resultSet stringForColumn:@"cache_data"];
            
            NSLog(@"%d, %@, %@", userId, cacheKey, cacheData);
        }
        
    }];
}


// 修改
- (void)updateWithItem:(id)item cacheKey:(NSString *)cacheKey {
    NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET cache_data=? WHERE cache_key = %@",_tableName,cacheKey];
    NSData *cacheData = [NSKeyedArchiver archivedDataWithRootObject:item];
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        BOOL result = [db executeUpdate:sql withArgumentsInArray:@[cacheData]];
        
        if (result) {
            NSLog(@"更新成功");
        }else {
            NSLog(@"更新失败");
        }
    }];
}

// 删除
- (void)deleteWithCacheKey:(NSString *)cacheKey {
    
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE cache_key = ?",_tableName];
    
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        BOOL result = [db executeUpdate:sql withArgumentsInArray:@[cacheKey]];
        
        if (result) {
            NSLog(@"delete成功");
        }else {
            NSLog(@"delete失败");
        }
        
    }];
}



#pragma mark - creatTable
- (void)createTableWithTableName:(NSString *)tableName {
    _tableName = tableName;
    NSString *createTableSql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ \n\
                                (id INTEGER PRIMARY KEY AUTOINCREMENT, \n\
                                cache_data BLOB NOT NULL, \n\
                                cache_key TEXT NOT NULL, \n\
                                time TEXT NOT NULL  DEFAULT (datetime('now', 'localtime'))\n\
                                )\n",tableName];
    
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        BOOL result = [db executeStatements:createTableSql];
        
        if (result) {
            NSLog(@"创建表成功");
        }else {
            NSLog(@"创建表失败");
        }
        
    }];
    
}

#pragma mark - getter
- (FMDatabaseQueue *)dbQueue {
    if(_dbQueue == nil)
    {
        _dbQueue = [FMDatabaseQueue databaseQueueWithPath:_dbPath];
    }
    return _dbQueue;
}



#pragma mark - 单例
- (instancetype)init {
    self = [super init];
    if (self) {
        
        [self createTableWithTableName:@"t_caches"];
    }
    return self;
}


static id _instance = nil;
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!_instance) {
            _instance = [[self alloc] init];
        }
    });
    
    return _instance;
}


+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    
    return _instance;
}

- (id)copyWithZone:(NSZone *)zone {
    return _instance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _instance;
}

@end
